package com.garen.app.jframe;

import java.awt.*;
import java.awt.event.*;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.garen.app.biz.TomcatBiz;

public class TomcatFrame extends JFrame{

	private static Log log = LogFactory.getLog(TomcatFrame.class);
	JButton []jbtns = null;
	private static String[] BTN_TEXT = {"启动","停止","打开首页"};
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static int DEFAULT_WIDTH = 400;
	private static int DEFAULT_HEIGHT = 280;
	
	private TomcatBiz tomcatbiz = null;
	
	public TomcatFrame(){
		init();
		initCompt();
		initTomcat();
		this.setVisible(true);
	}
	/*
	 * 更新状态
	 * 0 运行--服务运行中
	 * 1 停止--服务未运行
	 * 2 启动失败
	 * 3 停止失败
	 * */
	public void updateStatus(int status){
		for(JButton jbtn :jbtns){
			jbtn.setEnabled(false);
		}
		if(0 == status){
			jbtns[1].setEnabled(true);
		}if(1 == status){
			jbtns[0].setEnabled(true);
		}
	}
	//初始化tomcat参数
	private void initTomcat(){
		String jreHome = System.getProperty("java.home");
		File file = new File(jreHome);
		String jreName = file.getName();
		String basePath = file.getParent();
		String tomcatName = System.getProperty("tomcat.name");
		if(tomcatName == null) tomcatName = "tomcat";
		tomcatbiz = new TomcatBiz(basePath, jreName, tomcatName,this);
		if(tomcatbiz.checkStatus()) updateStatus(0);
		else updateStatus(1);
	}
	//初始化控件
	public void initCompt(){
		int btnLen = BTN_TEXT.length;
		jbtns = new JButton[btnLen];
		JPanel jp = new JPanel();
		for(int i = 0;i < btnLen;i++){
			jbtns[i] = new JButton(BTN_TEXT[i]);
			jbtns[i].addActionListener(btnLisener);
			jp.add(jbtns[i]);
		}
		this.add(jp);
	}
	//初始化窗口
	public void init(){
		this.setTitle("Tomcat管理");
		this.setResizable(false);
		this.setLocation(calcLocation(DEFAULT_WIDTH, DEFAULT_HEIGHT));
		this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	//计算位置
	static Point calcLocation(int width,int height){
		Toolkit kit = Toolkit.getDefaultToolkit();
		Dimension screensize = kit.getScreenSize();
		Point point = new Point();
		point.x = (screensize.width - width) / 2;
		point.y = (screensize.height - height) /2;
		return point;
	}
	//按钮事件
	private ActionListener btnLisener = new ActionListener(){
		@Override
		public void actionPerformed(ActionEvent e) {
			JButton jbtn = (JButton)e.getSource();
			String text = jbtn.getText();
			log.debug(text);
			if(BTN_TEXT[0].equals(text)){
				tomcatbiz.start();
				updateStatus(0);
			}else if(BTN_TEXT[1].equals(text)){
				tomcatbiz.stop();
				updateStatus(1);
			}else if(BTN_TEXT[2].equals(text)){
				//tomcatbiz.checkPort(1);
			}
		}
	};
		
	
}
